package imgshare.service.impl;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import imgshare.common.event.FollowCreatedEvent;
import imgshare.mapper.FollowMapper;
import imgshare.model.Follow;
import imgshare.model.FollowKey;
import imgshare.service.FollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FollowServiceImpl implements FollowService {

    private static final Log log = LogFactory.get();

    @Autowired
    private FollowMapper followMapper;
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Override
    public void createFollowRelation(FollowKey followKey) {
        int rowChanged = followMapper.insert(followKey);
        if (rowChanged == 0) {
            log.warn("followMapper.insert({}) 未能生效",followKey);
        } else {
            eventPublisher.publishEvent(new FollowCreatedEvent(this,followKey.getSubjectId(),followKey.getBeFollowedId()));
        }
    }

    @Override
    public Follow find(FollowKey followKey) {
        return followMapper.selectByPrimaryKey(followKey);
    }

    @Override
    public void switchFollow(Follow follow) {
        follow.setIsFollowing(!follow.getIsFollowing());
        int rowChanged = followMapper.updateByPrimaryKey(follow);
        if (rowChanged == 0) {
            log.warn("followMapper.updateByPrimaryKey({}}) 未能生效",follow);
        } else if (follow.getIsFollowing()) {
            eventPublisher.publishEvent(new FollowCreatedEvent(this,follow.getSubjectId(),follow.getBeFollowedId()));
        }
    }

    @Override
    public List<Integer> findMyFollowingUsersIds(Integer userId) {
        return followMapper.selectBeFollowedUsersIdBySubjectId(userId);
    }
}
